import { resolve } from 'path'
import { type UserConfigExport, type ConfigEnv, loadEnv } from 'vite'
import ip from 'ip'
import { createVitePlugins } from './build/vite'
import { include, exclude } from './build/vite/optimize'

// 获取ip地址
const ipStr = ip.address()
// 路径查找
const pathResolve = (dir: string): string => {
  return resolve(__dirname, dir)
}

// 跨域代理重写
const regExps = (value: string, reg: string): string => {
  return value.replace(new RegExp(reg, 'g'), '')
}

// https://vitejs.dev/config/
export default ({ command, mode }: ConfigEnv): UserConfigExport => {
  // 当前执行node命令时文件夹的地址(工作目录)
  const root = process.cwd()
  let env = {} as any
  // console.log(command)
  const isBuild = command === 'build'
  if (!isBuild) {
    // console.log(process.argv)
    env = loadEnv(process.argv[3] === '--mode' ? process.argv[4] : process.argv[3], root)
  } else {
    env = loadEnv(mode, root)
  }
  return {
    base: env.VITE_PUBLIC_PATH,
    root,
    // 开发服务
    server: {
      port: env.VITE_PORT,
      host: ipStr,
      hmr: true,
      // 本地跨域代理
      proxy:
        env.VITE_BASE_API_PATH.length > 0
          ? {
              [env.VITE_PROXY_API_PATH]: {
                target: env.VITE_BASE_API_PATH,
                changeOrigin: true,
                rewrite: (path: string) => regExps(path, env.VITE_PROXY_API_PATH)
              }
            }
          : undefined
    },
    // 生产环境配置
    build: {
      outDir: env.VITE_OUTDIR,
      assetsDir: 'assets/images',
      sourcemap: false,
      reportCompressedSize: false,
      // 消除打包大小超过500kb警告
      chunkSizeWarningLimit: 1024,
      minify: 'terser',
      target: 'esnext',
      // 清除console和debugger
      terserOptions: {
        compress: {
          drop_console: true,
          drop_debugger: true
        }
      },
      rollupOptions: {
        output: {
          chunkFileNames: chunkInfo => {
            const facadeModuleId = chunkInfo.facadeModuleId ? chunkInfo.facadeModuleId.split('/') : []
            let fileName = ''
            if (facadeModuleId.length > 0 && facadeModuleId[facadeModuleId.length - 1] === 'index.vue') {
              const index = facadeModuleId.indexOf('views')
              const idx = facadeModuleId.indexOf('src')
              if (idx > 0) {
                if (index > 0) {
                  fileName = 'vk_' + facadeModuleId.slice(index + 1, facadeModuleId.length - 1).join('_')
                } else {
                  fileName = 'vk_' + facadeModuleId.slice(idx + 1, facadeModuleId.length - 1).join('_')
                }
              } else {
                fileName = 'vk_[name]'
              }
            } else {
              fileName = 'vk_[name]'
            }
            return `assets/js/${fileName}-[hash].js`
          },
          entryFileNames: () => {
            return 'assets/js/vk_[name]-[hash].js'
          },
          assetFileNames: () => {
            return 'assets/[ext]/vk_[name]-[hash].[ext]'
          },
          manualChunks(id) {
            if (id.includes('node_modules')) {
              const currentPlugin = id.toString().split('node_modules/')[1].split('/')[0].toString()
              if (currentPlugin === 'lodash-es' || currentPlugin === '@vue' || currentPlugin === 'china-area-data' || currentPlugin === 'jsencrypt' || currentPlugin === 'crypto-js' || currentPlugin === 'xe-utils' || currentPlugin === 'zrender' || currentPlugin === 'echarts') {
                return currentPlugin
              } else if (currentPlugin === '@iconify') {
                const iconType = id.toString().split('node_modules/')[1].split('/')[3].split('.')[0].toString()
                return currentPlugin + '_' + iconType
              } else {
                return '_vendor'
              }
            } else {
              if (id.includes('/hooks/charts/mapCharts/map/')) {
                const currentPlugin = id.toString().split('/hooks/charts/mapCharts/map/')[1].split('.')[0].toString()
                return currentPlugin
              }
            }
          }
        }
      }
    },
    plugins: createVitePlugins(command, mode, env),
    // 依赖预构建，优化依赖，加速开发环境的启动和运行时性能
    optimizeDeps: { include, exclude },
    resolve: {
      extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.scss', '.css'],
      alias: {
        '@': pathResolve('src'),
        '^': pathResolve('build'),
        '#': pathResolve('types'),
        'vue-i18n': 'vue-i18n/dist/vue-i18n.cjs.js'
      }
    },
    css: {
      // css预处理器
      preprocessorOptions: {
        scss: {
          // 引入 variables.scss 这样就可以在全局中使用 variables.scss中预定义的变量了
          // 给导入的路径最后加上
          additionalData: `@use '@/style/variables.scss' as *;`,
          javascriptEnabled: true,
          api: 'modern-compiler'
        }
      }
    }
  }
}
